package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.CategoryCriteria;
import com.leo.ibatis.demo.dao.CategoryDao;
import com.leo.ibatis.demo.domain.Category;
import com.leo.ibatis.demo.util.Paging;

public class CategoryDaoImpl extends SqlMapClientDaoSupport implements CategoryDao {

	public void insert(Category category) throws DataAccessException {
		getSqlMapClientTemplate().insert("Category.insert", category);
	}

	public int update(Category category) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Category.update", category, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(String catid) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Category.delete", catid, actualRowsAffected);

		return actualRowsAffected;
	}

	public Category select(String catid) throws DataAccessException {
		return (Category) getSqlMapClientTemplate().queryForObject("Category.select", catid);
	}

	@SuppressWarnings("unchecked")
	public List<Category> list(CategoryCriteria categoryCriteria) throws DataAccessException {
		Assert.notNull(categoryCriteria, "categoryCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Category.list", categoryCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Category> listOnPage(CategoryCriteria categoryCriteria) throws DataAccessException {
		Assert.notNull(categoryCriteria, "categoryCriteria must not be null");
		Assert.notNull(categoryCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(categoryCriteria);
		Paging paging = categoryCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Category.list", categoryCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(CategoryCriteria categoryCriteria) throws DataAccessException {
		Assert.notNull(categoryCriteria, "categoryCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Category.count", categoryCriteria)).intValue();
	}

}
